﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Xml.Linq;
using System.Net;
using Microsoft.Surface.Presentation.Controls;
using System.ComponentModel;
using System.Windows.Markup;
using System.Windows.Threading;

namespace WikipediaSurfaceBrowser
{
    /// <summary>
    /// Interaction logic for WikiTopic.xaml
    /// </summary>
    public partial class WikiTopic : SurfaceUserControl
    {
        private string _topic = String.Empty;
        private const string WIKI_DATA = "http://{0}.wikipedia.org/w/api.php?action=query&prop=revisions&titles={1}&rvprop=content&format=xml&redirects";
        private const string COMMONS_IMAGES = "http://commons.wikimedia.org/w/api.php?action=query&prop=images&titles={0}&format=xml";
        private ApplicationSettings _settings = new ApplicationSettings();
        private Dictionary<string, string> _wikiLanguages = new Dictionary<string, string>();
        private WikiToXaml.WikiToXamlConvertor _convertor = new WikiToXaml.WikiToXamlConvertor();
        private BackgroundWorker _bw;
        private Stack<string> _historyBack = new Stack<string>();

        private FlowDocument _initDocument = null;
        
        private delegate void CallFromDispatcher(string s1, string s2);

        public WikiTopic()
        {
            InitializeComponent();
            Initialize();
                   
        }

        public WikiTopic(string wikiLanguage)
        {
            InitializeComponent();
            Initialize();
            this.WikiLanguage = wikiLanguage;
        }

        private void Initialize()
        {
            Uri uri = new Uri("/Resources/languages.txt", UriKind.Relative);
            System.Windows.Resources.StreamResourceInfo info = Application.GetContentStream(uri);
            StreamReader sr = new StreamReader(info.Stream);

            wiki.AddHandler(SurfaceButton.ClickEvent, new RoutedEventHandler(Hyperlink_Click));

            string line;
            string[] parts;
            while ((line = sr.ReadLine()) != null)
            {
                parts = line.Split(new char[] { ';' });
                _wikiLanguages.Add(parts[1], parts[0]);
            }  
        }

        
        void Hyperlink_Click(object sender, RoutedEventArgs e)
        {
            if (typeof(SurfaceButton) != e.OriginalSource.GetType())
            {
                return;
            }

            SurfaceButton b = (SurfaceButton) e.OriginalSource;

            if (this.SearchType == Search.TAG_COMMONS)
            {
                ShowImages(b.Tag.ToString());
            }
            else
            {
                this.Topic = b.Tag.ToString();
            }
        }

        private void ShowImages(string p)
        {
            ScatterView mainScatterView = (ScatterView)((ScatterViewItem)Parent).Parent;
            List<string> loadedImages = new List<string>();

            foreach (ScatterViewItem svi in mainScatterView.Items)
            {
                if (svi.Content.GetType() != typeof(ImagePad))
                {
                    continue;
                }

                loadedImages.Add(((ImagePad)svi.Content).SourceFileName);
            }

            XDocument doc = XDocument.Parse(ReadFromWeb(String.Format(COMMONS_IMAGES, p)));
            
            string[] images = (from i in doc.Descendants("im")                               
                               where (i.Attribute("title").Value.EndsWith("jpg") || i.Attribute("title").Value.EndsWith("png"))
                               select i.Attribute("title").Value).Distinct().ToArray<string>();

            foreach (string image in images)
            {
                try
                {
                    if (loadedImages.Contains(image.Substring(image.IndexOf(':') + 1)))
                    {
                        continue;
                    }

                    mainScatterView.Items.Add(new ScatterViewItem()
                    {
                        Content = new ImagePad() { Source = image }
                    });
                }
                catch (Exception e)
                {
                }
            }
        }

        public string RedirectFromTopic { get; set; }

        public string Topic
        {
            get
            {
                return _topic;
            }

            set
            {
                _topic = value;
                this.TitleLabel = _topic;
                
                _bw = new BackgroundWorker();
                _bw.DoWork += new DoWorkEventHandler(_bw_DoWork);
                _bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_bw_RunWorkerCompleted);
                _bw.RunWorkerAsync(_topic);

                doc.Document = _convertor.ConvertToFlowDocument("Načítám článek");                
                _historyBack.Push(_topic);                
            }
        }

        public String SearchType { get; set; }

        public String WikiLanguage { get; set; }

        public FlowDocument DocumentContent 
        { 
            get
            {
                return doc.Document;
            } 
            
            set
            {
                doc.Document = value;
                _initDocument = value;
            }
        }

        public string TitleLabel
        {
            get
            {
                return lblTitle.Content.ToString();
            }

            set
            {
                string label = Uri.UnescapeDataString(value).Replace("_", " ");
                int separator = label.IndexOf(':');

                if (separator > -1)
                {
                    label = label.Substring(separator + 1);
                }

                lblTitle.Content = label;
            }
        }

        void _bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            FlowDocument fd;
            try
            {
                fd = (FlowDocument)XamlReader.Parse((string)e.Result);
            }
            catch (Exception ex)
            {
                fd = _convertor.ConvertToFlowDocument(ex.Message);
            }
           
            doc.Document = fd;
            wiki.ScrollToHome();
        }

        void _bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bw = (BackgroundWorker)sender;
            e.Result = ReadWikiContent((string)e.Argument);
        }

        private string ReadFromWeb(string url)
        {            
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
            request.Accept = "text/xml";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader data = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
            return data.ReadToEnd();
        }

        private string ReadWikiContent(string title)
        {            
            _convertor.Language = this.WikiLanguage;

            Match m = Regex.Match(title, "([^:]{2,}):(.+)");

            if (m.Success)
            {
                if (_wikiLanguages.ContainsKey(m.Groups[1].Value))
                {
                    this.WikiLanguage = m.Groups[1].Value;
                    _convertor.Language = this.WikiLanguage;
                    title = m.Groups[2].Value;
                }
            }


            string wikiContent = ReadWikiContent(title, this.WikiLanguage, false);

            XDocument wikiContentDoc = XDocument.Parse(wikiContent);
            XElement redirects = wikiContentDoc.Descendants("r").FirstOrDefault<XElement>();
            XElement rev = wikiContentDoc.Descendants("rev").FirstOrDefault<XElement>();
            string fdXaml;

            if (redirects != null)
            {
                string from = redirects.Attribute("from").Value;
                string to = redirects.Attribute("to").Value;

                this.RedirectFromTopic = from;
                _topic = to;

                Dispatcher.BeginInvoke(new CallFromDispatcher(UpdateLabel), new object[] {from, to});                
            }

            try
            {

                if (rev != null)
                {
                    fdXaml = _convertor.ConvertToXaml(rev.Value);
                }
                else
                {
                    fdXaml = _convertor.ConvertToXaml(_settings.MissingTopic);
                }
            }
            catch (Exception e)
            {
                fdXaml = _convertor.ConvertToXaml(e.Message);
            }

            return fdXaml;
        }

        private void UpdateLabel(string s1, string s2)
        {
            lblTitle.Content = String.Format("{0} \u21D2 {1}", s1, s2);
        }

        private string ReadWikiContent(string title, string wikiLanguage, bool toCacheOnly)
        {
            string wikiCache = _settings.CacheFolder + System.IO.Path.DirectorySeparatorChar + wikiLanguage + System.IO.Path.DirectorySeparatorChar + title.Replace(":", "-") + ".xml";
            string wikiContent = String.Empty;
            if (File.Exists(wikiCache) && !toCacheOnly)
            {
                wikiContent = File.ReadAllText(wikiCache, Encoding.UTF8);
            }
            else
            {
                wikiContent = ReadFromWeb(String.Format(WIKI_DATA, wikiLanguage, title));

                if (!Directory.Exists(System.IO.Path.GetDirectoryName(wikiCache)))
                {
                    Directory.CreateDirectory(System.IO.Path.GetDirectoryName(wikiCache));
                }

                File.WriteAllText(wikiCache, wikiContent, Encoding.UTF8);
            }
            return wikiContent;
        }

        private void cmdClose_Click(object sender, RoutedEventArgs e)
        {
            ((ScatterView)((ScatterViewItem)Parent).Parent).Items.Remove(Parent);
        }

        private void cmdBack_Click(object sender, RoutedEventArgs e)
        {
            if ((_historyBack.Count > 0) && (_historyBack.Peek() == _topic))
            {
                _historyBack.Pop();
            }

            if ((_historyBack.Count == 0) && (_initDocument != null))
            {
                doc.Document = _initDocument;                
            }
            else if (_historyBack.Count > 0)
            {
                this.Topic = _historyBack.Pop();    
            }
        }      
    }
}